package org.springframework.samples.petclinic.lift.snippet

import javax.servlet.ServletContext
import java.util.HashMap

import scala.xml.{NodeSeq,Text}

import net.liftweb.http.{RequestVar,S,SHtml}
import net.liftweb.util.{Helpers,Log}

import Helpers._

import org.springframework.web.context.WebApplicationContext
import org.springframework.web.context.support.WebApplicationContextUtils
import org.springframework.context.MessageSource
import org.springframework.dao.DataAccessException
import org.springframework.validation.{MapBindingResult,BindingResult,FieldError,ObjectError}

import org.springframework.samples.petclinic.{Clinic,Owner,ForeachIterator}
import org.springframework.samples.petclinic.validation.OwnerValidator



class OwnerSnippet {

  // Set up a requestVar to track the object for edits and adds
  object ownerVar extends RequestVar(new Owner())
  def owner = ownerVar.is

  def add (xhtml : NodeSeq) : NodeSeq = {

    def doAdd () = {
      // Reusing the spring validator code
      val result = new MapBindingResult(new HashMap(), "owner")
      new OwnerValidator().validate(owner, result)
      LiftUtils.toLiftErrors(result)
      if (!result.hasErrors()) {
        try {
          LiftUtils.clinic.storeOwner(owner)
          S.redirectTo("/owner.do?ownerId=" + owner.id)
        } catch {
          case e : DataAccessException => error("DataAccessException")    
        }
      }
    }

    // Hold a val here so that the "id" closure holds it when we re-enter this method
    val currentId = owner.id
    
    val submitText = if (owner.isNew) "Add Owner" else "Update Owner"

    bind("owner", xhtml,
     "newText" -> (if (owner.isNew) "New " else ""),
     "id" -> SHtml.hidden(() => owner.id = currentId),
     "firstName" -> LiftUtils.field("First Name: ", owner.firstName, owner.firstName = _, "size" -> "30", "maxlength" -> "80", "id" -> "firstName"),
     "lastName" -> LiftUtils.field("Last Name: ", owner.lastName, owner.lastName = _, "size" -> "30", "maxlength" -> "80", "id" -> "lastName"),
     "address" -> LiftUtils.field("Address: ", owner.address, owner.address = _, "size" -> "30", "maxlength" -> "80", "id" -> "address"),
     "city" -> LiftUtils.field("City: ", owner.city, owner.city = _, "size" -> "30", "maxlength" -> "80", "id" -> "city"),
     "telephone" -> LiftUtils.field("Telephone:", owner.telephone, owner.telephone = _, "size" -> "20", "maxlength" -> "20", "id" -> "telephone"),
     "submit" -> <tr><td><p class="submit"> { SHtml.submit(submitText, doAdd) } </p></td></tr>
    )
  }
  
}
